const Base = require('./base.js');
const rp = require('request-promise');

module.exports = class extends Base {
  async loginByWeixinAction() {
    const code = this.post('code');
    const fullUserInfo = this.post('userInfo');
    const userInfo = fullUserInfo.userInfo;
    const clientIp = ''; // 暂时不记录 ip
    think.logger.info('loginByWeixinAction1:');
    // 获取openid
    const options = {
      method: 'GET',
      url: 'https://api.weixin.qq.com/sns/jscode2session',
      qs: {
        grant_type: 'authorization_code',
        js_code: code,
        secret: think.config('weixin.secret'),
        appid: think.config('weixin.appid')
      }
    };

    let sessionData = await rp(options);
    think.logger.info('sessionData stringify:' + sessionData);
    sessionData = JSON.parse(sessionData);
    think.logger.info('sessionData stringify:' + sessionData);
    think.logger.info('sessionData stringify:' + JSON.stringify(sessionData));
    if (!sessionData.openid) {
      think.logger.info('loginByWeixinAction 登录失败 1:');
      return this.fail('登录失败');
    }

    // 验证用户信息完整性
    const crypto = require('crypto');
    const sha1 = crypto.createHash('sha1').update(fullUserInfo.rawData + sessionData.session_key).digest('hex');
    if (fullUserInfo.signature !== sha1) {
      think.logger.info('loginByWeixinAction 登录失败 2:');
      return this.fail('登录失败');
    }

    // 解释用户数据
    const WeixinSerivce = this.service('weixin', 'api');
    const weixinUserInfo = await WeixinSerivce.decryptUserInfoData(sessionData.session_key, fullUserInfo.encryptedData, fullUserInfo.iv);
    if (think.isEmpty(weixinUserInfo)) {
      think.logger.info('loginByWeixinAction 登录失败 3:');
      return this.fail('登录失败');
    }

    let newFlag = false;
    // 根据openid查找用户是否已经注册
    let userId = await this.model('csshop_user').where({
      weixin_openid: sessionData.openid
    }).getField('id', true);
    if (think.isEmpty(userId)) {
      newFlag = true;
      think.logger.info('loginByWeixinAction 注注 1:');
      // 注册
      userId = await this.model('csshop_user').add({
        username: '微信用户' + think.uuid(6),
        password: sessionData.openid,
        register_time: parseInt(new Date().getTime() / 1000),
        register_ip: clientIp,
        last_login_time: parseInt(new Date().getTime() / 1000),
        last_login_ip: clientIp,
        mobile: '',
        weixin_openid: sessionData.openid,
        avatar: userInfo.avatarUrl || '',
        gender: userInfo.gender || 1, // 性别 0：未知、1：男、2：女
        nickname: userInfo.nickName
      });
    }

    sessionData.user_id = userId;

    // 查询用户信息
    const newUserInfo = await this.model('csshop_user').field(['id', 'mobile',
      'username', 'nickname', 'gender', 'avatar', 'birthday', 'rele_user_id'
    ]).where({
      id: userId
    }).find();

    // 更新登录信息
    userId = await this.model('csshop_user').where({
      id: userId
    }).update({
      last_login_time: parseInt(new Date().getTime() / 1000),
      last_login_ip: clientIp
    });

    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create(sessionData);

    if (think.isEmpty(newUserInfo) || think.isEmpty(sessionKey)) {
      think.log('loginByWeixinAction 登录失败 4:');
      return this.fail('登录失败');
    }
    
    think.logger.info("888888888888888888888888888");
    if (newUserInfo.rele_user_id) {
      const sysUserInfo = await this.model('v_sys_user').where({
        user_id: newUserInfo.rele_user_id
      }).find();
      think.logger.info('sysUserInfo1111111111111111');
      think.logger.info(sysUserInfo);
      think.logger.info('sysUserInfo222222222222222');
      newUserInfo.role_name = sysUserInfo.role_name;
      newUserInfo.company_name = sysUserInfo.company_name;
      newUserInfo.office_name = sysUserInfo.office_name;
      newUserInfo.company_id = sysUserInfo.company_id;
      newUserInfo.office_id = sysUserInfo.office_id;
      newUserInfo.name = sysUserInfo.name;
      newUserInfo.role_en_name = sysUserInfo.role_en_name;
      sessionData.role_en_name = sysUserInfo.role_en_name;

    }
    else
    {
      newUserInfo.rele_user_id ='';
      newUserInfo.role_en_name ='';
    }
    // await this.session('userInfo', newUserInfo);
    // const sfsf = await this.session('userInfo');
    think.logger.info(newUserInfo);
    return this.success({
      token: sessionKey,
      code: '0',
      userInfo: newUserInfo
    });
  }

  async logoutAction() {
    return this.success();
  }
};